<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use DB;
use App\Topic;
use App\Vote;

class IndexController extends Controller
{
    public function index() {
        $topics = new Topic;
        $data = $topics->getTopics(); //获取到话题信息
        $data = $this->addOtherInfo($data); //添加其他信息，发布者昵称，参与人数
        $hots = $this->getHots();
        return view('index', ['data' => $data, 'hots' => $hots]);
    }

    public function searchGet(Request $req, $key = '')
    {
        //跳转到投票界面
        $topics = new Topic;
        
        $data = $topics->searchTopics($key);

        //debug
        //$data = [];
        //echo count($data);

        $hots = $this->getHots();

        //主界面
        return view('index', ['data' => $data, 'hots' => $hots]);
    }

    public function searchPost(Request $req)
    {
        //跳转到投票界面
        $topics = new Topic;
        $data = $topics->searchTopics($req->keywords);
        
        return redirect("/search/".$req->keywords);
    }

    public function vote(Request $req, $tid)
    {
        $vote = new Vote();
        if ($vote->isVoted($tid, $req->getClientIp())) { //已经投过票了
//            return '您已经投过票了';
            return redirect('/result/'.$tid);
        } else { //没有投过票
            //调用model层接口
            $topic = new Topic();
            $data = $topic->getTopic($tid);
            $data = $this->addOtherInfoForOne($data);
            return view('vote', ['data' => $data, 'tid' => $tid]);
        }
    }

    public function votePost(Request $req)
    {
        //判断如果用户已经投过票了提示
        $vote = new Vote();
        if ($vote->isVoted($req->topic_id, $req->getClientIp())) { //已经投过票了
            return '您已经投过票了';
        }

        $sel_array = [];

        if ($_POST['type'] == 'checkbox') {
            foreach ($_POST as $k => $v) {
                if (strpos($k, 'select') !== false) {
                    $sel_array[] = $v;
                }
            }
        } else {
            if (isset($req->select))
                $sel_array[] = $req->select;
        }

        //todo 暂时现在这里做个保护，如果用户没有选择点了提交还是跳回到本页面，应该用js来判断
        if (count($sel_array) == 0) {
            return redirect('/vote/'.$req->topic_id);
        }
        $uid = $req->user() === null ? '' : $req->user()->uid;
        $vote->vote($req->topic_id, $uid, $req->getClientIp(), $sel_array);

        return redirect('/result/'.$req->topic_id);
    }

    public function showResult($tid) {
        $v = new Vote;

        //todo 统计结果
        $result = $v->getResult($tid);

        //todo 展示结果
        $topic = new Topic();
        $data = $topic->getTopic($tid);

        foreach ($data['selects'] as $k => $v) {
            $sid = $v['sid'];
            if (isset($result[$sid])) {
                $data['selects'][$k]['num'] = $result[$sid]['num'];
                $data['selects'][$k]['percent'] = $result[$sid]['percent'];
            } else {
                $data['selects'][$k]['num'] = 0;
                $data['selects'][$k]['percent'] = 0;
            }
        }

        //排序
        for ($i = 0; $i < count($data['selects']) - 1; $i++) {
            for ($j = $i + 1; $j < count($data['selects']); $j++) {
                if ($data['selects'][$i]['num'] < $data['selects'][$j]['num']) {
                    list($data['selects'][$i], $data['selects'][$j]) = array($data['selects'][$j], $data['selects'][$i]);
                }
            }
        }

        $data = $this->addOtherInfoForOne($data);

        return view('result', ['data' => $data, 'tid' => $tid, 'show_result' => true]);
    }

    /**
     * 获取热门话题
     * @return mixed
     */
    public function getHots() {
        return DB::select('select a.tid, title, count(*) as person from (select tid, ip from votes group by tid, ip) as a inner join topics on a.tid = topics.tid group by tid order by person desc');
    }

    /**
     * 往查询数组中添加其他信息，例如，发布者昵称，参与人数
     * 现在这种实现方式有点复杂，肯定有简单的方式可以实现
     * @todo 优化实现逻辑
     * @param $data
     * @return mixed
     */
    public function addOtherInfo($data) {
        $info = DB::select('select top.*, ifnull(vot.person, 0) as person
                            from
                            (select a.tid, a.title, a.desc, a.pub_time, b.name
                            from topics as a
                            inner join users as b
                            on a.uid = b.uid) as top
                            left join 
                            (select tid, count(*) as person from (select tid, ip from votes group by tid, ip) as a group by tid) as vot
                            on top.tid = vot.tid
                            order by pub_time desc');

        $info_t = [];

        foreach ($info as $i) {
            $info_t[$i->tid] = $i;
        }

        foreach ($data as $d) {
            $d['person'] = $info_t[$d['tid']]->person;
            $d['name'] = $info_t[$d['tid']]->name;
        }

        return $data;
    }

    /**
     * 往查询数组中添加其他信息，例如，发布者昵称，参与人数
     * 现在这种实现方式有点复杂，肯定有简单的方式可以实现
     * @todo 优化实现逻辑
     * @param $data
     * @return mixed
     */
    public function addOtherInfoForOne($data) {
        $info = DB::select('select top.*, ifnull(vot.person, 0) as person
                            from
                            (select a.tid, a.title, a.desc, a.pub_time, b.name
                            from topics as a
                            inner join users as b
                            on a.uid = b.uid) as top
                            left join 
                            (select tid, count(*) as person from (select tid, ip from votes group by tid, ip) as a group by tid) as vot
                            on top.tid = vot.tid
                            order by pub_time desc');

        $info_t = [];

        foreach ($info as $i) {
            $info_t[$i->tid] = $i;
        }

        $data['person'] = $info_t[$data['tid']]->person;
        $data['name'] = $info_t[$data['tid']]->name;

        return $data;
    }
}







